const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");

const userSchema = new mongoose.Schema(
    {
        username: {
            type: String,
            required: true,
            unique: true,
            minlength: 2,
            maxlength: 32,
            index: true,
        },
        email: {
            type: String,
            required: true,
            unique: true,
            lowercase: true,
            match: /.+\@.+\..+/,
            index: true,
        },
        password: {
            type: String,
            required: true,
            select: false, // 默认查询不返回密码
        },
        role: {
            type: String,
            enum: ["user", "admin"],
            default: "user",
            index: true,
        },
        bio: { type: String, default: "" },
        avatarUrl: { type: String, default: "" },
    },
    { timestamps: true }
);

// 保存前加密密码（仅在密码被修改时）
userSchema.pre("save", async function (next) {
    if (!this.isModified("password")) return next();
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
});

// 实例方法：校验密码
userSchema.methods.comparePassword = function (plain) {
    return bcrypt.compare(plain, this.password);
};

// 统一输出：隐藏敏感字段
userSchema.set("toJSON", {
    transform: (doc, ret) => {
        delete ret.password;
        delete ret.__v;
        return ret;
    },
});

module.exports = mongoose.model("User", userSchema);
